package com.lastcode6175.bluetoothremotecontrol

import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.util.Log
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlin.math.abs

/**
 * 飞鼠模式控制器 - 使用设备陀螺仪数据控制鼠标光标
 */
class GyroMouseController(private val context: Context) : SensorEventListener {
    private val sensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
    private val gyroscopeSensor = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE)
    
    private val _isActive = MutableStateFlow(false)
    val isActive = _isActive.asStateFlow()
    
    private val coroutineScope = CoroutineScope(Dispatchers.Main)
    private var sensorJob: Job? = null
    
    // 陀螺仪数据
    private var rotationX = 0f
    private var rotationY = 0f
    private var rotationZ = 0f
    
    // 灵敏度设置 (可调整)
    private var sensitivity = 37.5f
    
    // 鼠标移动回调
    var onMouseMove: ((dx: Int, dy: Int) -> Unit)? = null
    
    /**
     * 启动飞鼠模式
     */
    fun start() {
        if (_isActive.value) return
        
        if (gyroscopeSensor == null) {
            Log.e("GyroMouseController", "设备不支持陀螺仪传感器")
            return
        }
        
        _isActive.value = true
        sensorManager.registerListener(this, gyroscopeSensor, SensorManager.SENSOR_DELAY_GAME)
        
        // 启动处理协程
        sensorJob = coroutineScope.launch {
            while (isActive && _isActive.value) {
                processGyroData()
                delay(16) // 约60Hz的更新频率
            }
        }
        
        Log.d("GyroMouseController", "飞鼠模式已启动")
    }
    
    /**
     * 停止飞鼠模式
     */
    fun stop() {
        if (!_isActive.value) return
        
        _isActive.value = false
        sensorManager.unregisterListener(this)
        sensorJob?.cancel()
        sensorJob = null
        
        // 重置数据
        rotationX = 0f
        rotationY = 0f
        rotationZ = 0f
        
        Log.d("GyroMouseController", "飞鼠模式已停止")
    }
    
    /**
     * 设置灵敏度
     */
    fun setSensitivity(value: Float) {
        sensitivity = value.coerceIn(1f, 30f)
    }
    
    /**
     * 处理陀螺仪数据并转换为鼠标移动
     */
    private fun processGyroData() {
        if (!_isActive.value) return
        
        // 计算鼠标移动量
        // 注意：我们将Z轴旋转映射到X轴移动，X轴旋转映射到Y轴移动
        val dx = (-rotationZ * sensitivity).toInt()
        val dy = (-rotationX * sensitivity).toInt() // 反转Y轴以匹配屏幕坐标系
        
        // 应用死区 - 忽略很小的移动
        if (abs(dx) > 1 || abs(dy) > 1) {
            onMouseMove?.invoke(dx, dy)
        }
    }
    
    override fun onSensorChanged(event: SensorEvent) {
        if (event.sensor.type == Sensor.TYPE_GYROSCOPE) {
            // 更新旋转数据
            rotationX = event.values[0] // 绕X轴旋转
            rotationY = event.values[1] // 绕Y轴旋转
            rotationZ = event.values[2] // 绕Z轴旋转
        }
    }
    
    override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) {
        // 不需要处理精度变化
    }
}